package com.leetcode;

import com.leetcode.common.ListNode;

import static com.leetcode.util.LinkedListUtil.createList;
import static com.leetcode.util.LinkedListUtil.printList;

/**
 * 2. 两数相加
 *
 * @author fy
 * @date 2022/3/31 19:39
 */
public class Solution2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(-1);
        ListNode cur = dummyHead;
        int carry = 0;
        while (l1 != null && l2 != null) {
            int val = carry + l1.val + l2.val;
            carry = val / 10;
            val = val % 10;

            cur.next = new ListNode(val);

            cur = cur.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null) {
            int val = carry + l1.val;
            carry = val / 10;
            val = val % 10;
            cur.next = new ListNode(val);

            cur = cur.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            int val = carry + l2.val;
            carry = val / 10;
            val = val % 10;
            cur.next = new ListNode(val);

            cur = cur.next;
            l2 = l2.next;
        }
        if (carry > 0) {
            cur.next = new ListNode(carry);
        }
        return dummyHead.next;
    }

    public ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        ListNode head = new ListNode(0);
        ListNode cur = head;

        int carry = 0;
        while (cur1 != null || cur2 != null) {
            int val = carry;
            carry = 0;
            if (cur1 != null) {
                val += cur1.val;
                cur1 = cur1.next;
            }
            if (cur2 != null) {
                val += cur2.val;
                cur2 = cur2.next;
            }
            if (val > 9) {
                carry = val / 10;
                val = val % 10;
            }
            cur.next = new ListNode(val);
            cur = cur.next;
        }
        if (carry != 0) {
            cur.next = new ListNode(carry);
        }
        return head.next;
    }

    public static void main(String[] args) {
//        ListNode l1 = new ListNode(2);
//        ListNode l12 = new ListNode(4);
//        ListNode l13 = new ListNode(3);
//        l1.next = l12;
//        l12.next = l13;
//
//        ListNode l2 = new ListNode(5);
//        ListNode l22 = new ListNode(6);
//        ListNode l23 = new ListNode(4);
//        l2.next = l22;
//        l22.next = l23;

//        ListNode l1 = createList(new int[]{2, 4, 3});
//        ListNode l2 = createList(new int[]{5, 6, 4});
        ListNode l1 = createList(new int[]{9, 9, 9, 9, 9, 9});
        ListNode l2 = createList(new int[]{9, 9, 9});

        ListNode head = new Solution2().addTwoNumbers(l1, l2);

        printList(head);
    }

}
